package com.cssl.config;

import cn.dev33.satoken.reactor.filter.SaReactorFilter;
import cn.dev33.satoken.router.SaRouter;
import com.cssl.util.StpKit;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;


@Configuration
public class SaTokenConfigure {


    @Bean
    public SaReactorFilter getSaReactorFilter() {
        return new SaReactorFilter()
                // 拦截地址
                .addInclude("/**")    /* 拦截全部path */
                // 开放地址
                .addExclude("/favicon.ico")
                // 鉴权方法：每次访问进入
                .setAuth(obj -> {
                    SaRouter.match("/**").notMatch("/admin/login", "/admin/getCaptcha").check(r -> StpKit.ADMIN.checkLogin());
                })
                .setAuth(obj -> {
                    Map<String, String> rules = getAuthRules();
                    for (String path : rules.keySet()) {
                        SaRouter.match(path, () -> StpKit.ADMIN.checkPermission(rules.get(path)));
                    }
                })
                //自定义异常返回
                .setError(e -> e);
    }


    /**
     * 动态添加权限规则
     *
     * @return
     */
    public Map<String, String> getAuthRules() {
        Map<String, String> authMap = new LinkedHashMap<>();
        authMap.put("/goods/goodsList", "admin:goods:read");
        authMap.put("/brand/getBrandList", "admin:goods:read");
        authMap.put("/category/getCategory", "admin:goods:read");
        authMap.put("/goods/getGoodsAllInfoById", "admin:goods:read");
        authMap.put("/comment/getCommentVOGoodsList", "admin:goods:read");
        authMap.put("/goods/goodsInOrder", "admin:goods:read");
        authMap.put("/goods/goodsOnShelf", "admin:goods:create");
        authMap.put("/goods/updateGoodsAllInfoById", "admin:goods:update");
        authMap.put("/goods/deleteGoodsById", "admin:goods:delete");
        authMap.put("/admin/createAdmin/**", "*");
        authMap.put("/admin/updateAdmin/**", "*");
        authMap.put("/admin/deleteAdmin/**", "*");
        authMap.put("/role/createRole/**", "*");
        authMap.put("/role/updateRole/**", "*");
        authMap.put("/role/deleteRole/**", "*");
        return authMap;
    }
}
